﻿layui.define(['jquery', 'timemsg'], function (exports) {
	var $ = layui.jquery
	var language = {
			errorLoading: function () {
				return '无法载入结果。'
			},
			inputTooLong: function (n) {
				return '请删除' + (n.input.length - n.maximum) + '个字符'
			},
			inputTooShort: function (n) {
				return '请再输入至少' + (n.minimum - n.input.length) + '个字符'
			},
			loadingMore: function () {
				return '载入更多结果…'
			},
			maximumSelected: function (n) {
				return '最多只能选择' + n.maximum + '个项目'
			},
			noResults: function () {
				return '未找到结果'
			},
			searching: function () {
				return '搜索中…'
			},
			removeAllItems: function () {
				return '删除所有项目'
			}
		},
		elimOptions = ['url', 'method', 'dataType', 'selected', 'data', 'initData', 'pagesize', 'valueField', 'textField', '$form', 'endFn'] //非 select2 原配置项
	var obj = {
		open: function ($selectId, options) {
			var iData = {
					url: '',
					method: 'post',
					dataType: 'json',
					width: '100%',
					placeholder: '请选择',
					allowClear: true, //允许清除
					minimumResultsForSearch: undefined,
					maximumSelectionLength: 0,
					selected: null,
					data: {},
					initData: [], //本地数据选项
					pagesize: 10,
					valueField: 'DictCode',
					textField: 'DictConfigName',
					$form: $(document),
					endFn: null // 这是select2完成请求之后调用的方法
				},
				$select
			// if (!selectId) return
			$.extend(iData, options)
			if (typeof $selectId === 'string') {
				$select = iData.$form.find($selectId)
			} else if ($selectId instanceof jQuery) $select = $selectId
			else return

			if ($select.length === 0 || $select[0].tagName != 'SELECT') return
			if (!!iData.selected && iData.selected.length != 0 && (!!iData.selected[0].defaultId || iData.selected[0].defaultId === 0)) {
				// 默认选中项设置
				var html = ''
				var values = []
				var selected = iData.selected
				$.each(selected, function (index, item) {
					values.push(item.defaultId)
					html += '<option value="' + item.defaultId + '">' + (item.defaultValue || '') + '</option>'
				})
				$select.append(html)
				$select.val(values).trigger('change')

				//还原选中项
				$select.on('select2:select', function (e) {
					var $this = $(this),
						$parent = $this.parent()
					if ($parent.find('.select2Res').length > 0) {
						return
					}
					$parent.append('<i class="layui-icon layui-icon-refresh-1 select2Res" title="还原选中项"></i>')
					$parent.find('.select2Res').click(function (e) {
						$this.val(values).trigger('change')
						$(this).remove()
					})
				})
			}

			if (!options.initData && !options.url) return //数据源参数不存在说明只是为了赋值 selected

			select2Options = $.extend(true, {}, iData)
			elimOptions.forEach(function (item) {
				delete select2Options[item]
			})

			$select.select2(
				$.extend(
					{
						language: language,
						/* width: iData.width,
						placeholder: iData.placeholder,
						allowClear: iData.allowClear,
						minimumResultsForSearch: iData.minimumResultsForSearch,
						maximumSelectionLength: iData.maximumSelectionLength, */
						data: iData.initData,
						ajax: iData.url
							? {
									url: iData.url,
									method: iData.method,
									dataType: iData.dataType,
									data: function (params) {
										var data_obj = {
											// 搜索框内输入的内容
											keyword: params.term || '',
											// 当前页
											page: params.page || 1,
											// 每页显示多少条记录，默认10条
											rows: iData.pagesize
										}
										$.extend(iData.data, data_obj)
										return iData.data
									},
									cache: true,
									processResults: function (res, params) {
										if (res.success == false && res.message == '您尚未登录') {
											this.$element.select2('close')
											layui.timemsg.open({
												text: res.message + ' 或 登录时间过期',
												done: function () {
													window.location.href = '/sys_Account/Login?ReturnUrl=' + window.location.href
												}
											})
											return { results: [{ id: 0, text: '登录过期' }] }
										} else {
											params.page = params.page || 1
											var rs_str = JSON.stringify(res.rows || res)
													.replace(new RegExp(iData.valueField, 'g'), 'id')
													.replace(new RegExp(iData.textField, 'g'), 'text'),
												rs = JSON.parse(rs_str)
											!!iData.endFn && iData.endFn(res)
											return {
												results: rs,
												pagination: {
													more: params.page * iData.pagesize < res.total
												}
											}
										}
									},
									escapeMarkup: function (markup) {
										return markup
									} // 自定义格式化防止xss注入
							  }
							: undefined
					},
					select2Options
				)
			)
		}
	}
	//输出接口
	exports('select2', obj)
})
